package com.carol.bigdata.utils

import java.lang.reflect.Method
import java.util

import org.javatuples.Triplet
import org.lionsoul.ip2region.{DataBlock, DbSearcher, Util}


object IpTool extends Serializable {

    def getSearcher(dbPath: String): DbSearcher = {
        new IpUtil(dbPath).searcher
    }

    def parseIp(searcher: DbSearcher, ip: String, algorithm: String="btreeSearch"): Triplet[String, String, String] = {
        var code: String = "0"
        var message: String = "ok"
        var data: String = ""
        var res = new Triplet[String, String, String](code, message, data)
        // 判断是否是ip地址
        if (!Util.isIpAddress(ip)) {
            code = "1000"
            message = "Error: Invalid ip address"
            res = new Triplet[String, String, String](code, message, data)
        }
        try {
            //define the method
            val method: Method = searcher.getClass.getMethod(algorithm, classOf[String])
            val dataBlock: DataBlock = method.invoke(searcher, ip).asInstanceOf[DataBlock]
            data = dataBlock.getRegion
            res = new Triplet[String, String, String](code, message, data)
        } catch {
            case e: Exception =>
                code = "1000"
                message = "查询算法出错"
                e.printStackTrace()
                res = new Triplet[String, String, String](code, message, data)
        }
        res
    }

    def getCityInfo(searcher: DbSearcher, ip: String, algorithm: String="btreeSearch"): util.HashMap[String, String] = {
        val res: util.HashMap[String, String] = new util.HashMap[String, String]
        val triplet: Triplet[String, String, String] = parseIp(searcher, ip, algorithm=algorithm)
        res.put("code", triplet.getValue0)
        res.put("message", triplet.getValue1)
        // 中国|0|上海|上海市|联通
        val dataStr: String = triplet.getValue2
        val split: Array[String] = dataStr.split("\\|")
        if (split.length == 5) {
            res.put("country", split(0))
            res.put("province", if (split(2) == "0") split(3)
            else split(2))
            res.put("city", if (split(3) == "0") split(2)
            else split(3))
            res.put("network", split(4))
        }
        res
    }

}
